package com.clj.blesample.notication;

import android.app.Notification;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.text.TextUtils;
import android.util.Log;

import com.clj.fastble.entity.MessageEntity;

import org.greenrobot.eventbus.EventBus;

public class NotificationService extends NotificationListenerService {

    // 在收到消息时触发
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        // 获取接收消息APP的包名
        String notificationPkg = sbn.getPackageName();
        Bundle extras = sbn.getNotification().extras;
        // 获取接收消息的抬头
        String notificationTitle = (String) extras.getString(Notification.EXTRA_TITLE);
        // 获取接收消息的内容
        CharSequence notificationContentData = extras.getCharSequence(Notification.EXTRA_TEXT);
        if (notificationContentData == null) {
            return;
        }
        String notificationContent = notificationContentData.toString();
        Log.d("FastBle","通知栏 包名= " + notificationPkg + ", 标题 = "+ notificationTitle + ",内容 = " +notificationContent);
        if (TextUtils.isEmpty(notificationPkg) || TextUtils.isEmpty(notificationTitle) || TextUtils.isEmpty(notificationContent)) {
            return;
        }

        if (!WatchBleUtils.isListentNoticationPkg(notificationPkg)) {
            Log.d("FastBle","过滤不是手表监听数据的应用 = " + notificationPkg);
            return;
        }
        String formatContent = WatchBleUtils.convertContent(getApplication(), notificationPkg, notificationTitle, notificationContent);
        if (TextUtils.isEmpty(formatContent)) {
            return;
        }
        notificationPkg = ByteUtil.convertPakageName(notificationPkg);
        MessageEntity msg = new MessageEntity();
        msg.setPkg(notificationPkg);
        msg.setTitle(WatchBleUtils.getNoticationTitle(getApplicationContext(),notificationPkg,notificationTitle,notificationContent));
        msg.setText(formatContent);
        msg.setType(2);
        msg.setPost(true);//用以区分是post还是removed
        EventBus.getDefault().post(msg);
    }

    // 在删除消息时触发
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {

    }
}
